package com.sgj.gulimall.search.thread;


import java.util.Objects;
import java.util.concurrent.*;

/**
 * @Author: Guoji Shen
 * @Date: 2021/7/28 9:11
 */
public class ThreadTest {

    // 异常返回码
    public static final Integer EXCEPTIONCODE = 500;

    // 一个系统只能1-2个线程池，每个异步任务，提交给线程池执行即可
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main....start.....");

        // CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("运行结果：" + i);
        // }, executor);


        // 方法完成后的感知
        // CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 0;
        //     System.out.println("运行结果：" + i);
        //     return i;
        // }, executor).whenComplete((res, exception) -> {
        //     System.out.println("异步任务完成了，结果是：" + res + "，异常是：" + exception);
        // }).exceptionally(throwable -> {
        //     // 自定义异常返回结果
        //     return EXCEPTIONCODE;
        // });
        // Integer integer = future.get();
        // System.out.println(integer);


        // 方法完成后的处理
        // CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("运行结果：" + i);
        //     return i;
        // }, executor).handle((res, exception) -> {
        //     if (Objects.nonNull(res)) {
        //         return res * 10;
        //     }
        //     if (Objects.nonNull(exception)) {
        //         return EXCEPTIONCODE;
        //     }
        //     return EXCEPTIONCODE;
        // });
        // Integer integer = future.get();
        // System.out.println(integer);


        // CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("运行结果：" + i);
        //     return i;
        // }, executor).thenRunAsync(() -> {
        //     System.out.println("第二个异步任务启动了");
        // }, executor);


        // CompletableFuture.supplyAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("运行结果：" + i);
        //     return i;
        // }, executor).thenAcceptAsync(res -> {
        //     // res 为上一个异步 return 的值
        //     System.out.println("第二个异步任务启动了:" + res);
        // }, executor);


        // CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("当前线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("运行结果：" + i);
        //     return i;
        // }, executor).thenApplyAsync(res -> {
        //     // res 为上一个异步 return 的值
        //     System.out.println("第二个异步任务启动了:" + res);
        //     return "我有" + res * 10 + "块钱";
        // }, executor);
        // String string = future.get();
        // System.out.println(string);


        // CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("任务1线程：" + Thread.currentThread().getId());
        //     int i = 10 / 2;
        //     System.out.println("任务1结束：" + i);
        //     return i;
        // }, executor);
        //
        // CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
        //     System.out.println("任务2线程：" + Thread.currentThread().getId());
        //     String s = "Hello";
        //     try {
        //         Thread.sleep(3000);
        //         System.out.println("任务2结束：" + s);
        //     } catch (InterruptedException e) {
        //         e.printStackTrace();
        //     }
        //     return s;
        // }, executor);

        // future01.runAfterBothAsync(future02, () -> {
        //     System.out.println("任务3开始");
        // }, executor);

        // future01.thenAcceptBothAsync(future02, (f1, f2) -> {
        //     System.out.println(f2 + ", " + f1);
        // }, executor);

        // CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
        //     return f2 + ": " + f1 + " -> Haha";
        // }, executor);
        // System.out.println(future.get());

        // future01.runAfterEitherAsync(future02, () -> {
        //     System.out.println("任务3开始");
        // }, executor);

        // future01.acceptEitherAsync(future02, res -> {
        //     System.out.println(res);
        // }, executor);

        // CompletableFuture<String> future = future01.applyToEitherAsync(future02, res -> res.toString() + " -> 哈哈", executor);
        // String s = future.get();
        // System.out.println(s);

        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的图片信息");
            return "hello.jpg";
        }, executor);

        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("查询商品的属性");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "黑色+256G";
        }, executor);

        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询商品的介绍");
            return "华为";
        }, executor);

        // CompletableFuture<Void> future = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        CompletableFuture<Object> future = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);
        future.get();
        System.out.println(futureImg.get() + " -> " + futureAttr.get() + " -> " + futureDesc.get());

        System.out.println("main....end.....");
    }

    public void thread() throws ExecutionException, InterruptedException {
        System.out.println("main....start.....");

        // 继承 Thread 接口
        // Thread01 thread = new Thread01();
        // thread.start();

        // 实现 Runable 接口
        // Runable01 runable = new Runable01();
        // new Thread(runable).start();

        // 继承 Callable 接口
        // FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
        // new Thread(futureTask).start();
        // // 阻塞等待整个线程执行完成，获取返回结果
        // Integer integer = futureTask.get();
        // System.out.println(integer);

        // 模拟线程池执行线程
        // service.execute(new Runable01());

        /**
         * 七大参数
         * corePoolSize：核心线程数(只要线程池不销毁，就一直存在，除非allowCoreThreadTimeOut)，线程池创建好就准备就绪的线程数量，等待异步任务去执行
         * maximumPoolSize：最大线程数量，控制资源
         * keepAliveTime：存活时间，当前如果正在运行的线程数量，大于core数量时，会释放空闲线程(maximumPoolSize - corePoolSize)，只要线程空闲大于指定的存活时间
         * unit：时间单位
         * workQueue：阻塞队列，如果任务有很多，就会将目前多余的任务放在阻塞队列内。只要线程空闲，就会从阻塞队列中拿出任务执行。
         * threadFactory：线程的创建工厂。
         * handler：如果队列满了，按照指定的拒绝策略，拒绝执行任务。
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                // AbortPolicy：直接丢弃任务
                new ThreadPoolExecutor.AbortPolicy()
                );

        System.out.println("main....end.....");
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Runable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Callable01 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }
}